# Created by Gao Song on 2022-02-15

from .rq import rq

future_exchanges = {'CFFEX', 'SHFE', 'DCE', 'CZCE', 'INE','GFEX'}
stock_exchanges = {'XSHG', 'XSHE'}


def symbol_type(symbol):
    exchange = symbol.split('.')[1]
    if exchange in stock_exchanges:
        return 'stock'
    if exchange in future_exchanges:
        return 'future'
    return None


def lq_to_rq_symbol(symbol):
    sec_id, exchange = symbol.split('.')

    res = None
    if exchange in stock_exchanges:
        res = symbol
    elif exchange in future_exchanges:
        if exchange == 'CZCE':
            res = rq.id_convert(sec_id)
        else:
            res = sec_id.upper()
    return res


def rq_to_lq_symbol(symbol):
    res = None
    if '.' in symbol:
        sec_id, exchange = symbol.split('.')
        if exchange in stock_exchanges:
            res = symbol
    else:
        ins = rq.instruments(symbol)
        res = f'{ins.trading_code}.{ins.exchange}'
    return res


def convert_to_rq_stock_symbol(symbol):
    if symbol.startswith(('0', '3')):
        return symbol + ".XSHE"
    elif symbol.startswith(('5', '6', '9', '15')):
        return symbol + ".XSHG"
    else:
        raise Exception(f'can not convert {symbol}')


def contract_to_commodity(contract_name):
    return ''.join([x for x in contract_name if not x.isdigit()]).upper()
